<?php
namespace app\money\controller;
use app\admin\common\Base;
use think\Db;
//收款单
class Receipt extends Base
{
    public function index()
    {
        
        $data = $this->request->param();

        $this->assign('o_type',10);//高级搜索状态（10：收款单记录）

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['search'])) {

                if ($data['search'] == 0) {

                    $field = 'sn|mark';
                    $sonField = 'name';
                    $keywork = $data['matchCon'];
                    $value = ['customer','user_id'];
                    $where = getSearch($field, $sonField, $keywork, $value);

                    $time1 = strtotime($data['datew']);
                    $time2 = strtotime($data['dateo']);

                    $sql = Db::name('payment')->where('type', 0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where($where);
                    $sql = !isset($time1) && !isset($time2) ? $sql :$sql->whereTime('dj_time','between',[$time1,$time2]);
                    $list = $sql->order('id desc')->limit($start, $limit)->select();
                    $count = sizeof($list);

                //高级搜索
                }else{
                    // halt($data);
                    $stime = [$data['fromDate'],$data['toDate']];
                    $tables = ['user_id','add_user','last_user','shenhe_user','status'];
                    $keywork = [$data['customer_id'],$data['usersCreatId'],$data['usersModifyId'],$data['usersChecksId'],$data['checkStatusId']];
                    //模糊查询子表
                    $pay = empty($data['remarkCon']) ? null : Db::name('account_record')->where(['is_del' => 0,'enterprise_id' => $this->EnterpriseId])->where('mark','like','%'.$data['remarkCon'].'%')->column('pid');
                    $sql = Db::name('payment')->where('is_del', 0)->where('type', 0)->where('enterprise_id',$this->EnterpriseId);
                    //获取时间值 用于判断
                    $sql = empty($stime[0]) && empty($stime[1]) ? $sql : $sql->whereTime('dj_time','between',$stime);
                    //精确查询
                    $sql = empty($pay) ? $sql : $sql->where('id','in',$pay);
                    for ($j=0; $j <count($keywork) ; $j++) {
                        $sql = $keywork[$j] == '' ? $sql : $sql->where($tables[$j],$keywork[$j]);
                    }
                        $list = $sql->order('id desc')->limit($start, $limit)->select();
                        $count = sizeof($list);
                }
            }else{
                if ($map == '') {
                    $list = Db::name('payment')->where('type',0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                    $count = Db::name('payment')->where('type',0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                } else {
                    $list = Db::name('payment')->where('type',0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('id desc')->limit($start, $limit)->select();
                    $count = Db::name('payment')->where('type',0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
                }
            }   
                foreach ($list as $key => &$val) {
                    $move_good=Db::name('account_record')->where('psn',$val['sn'])->select();
                    $account_name=[];//结算账户名称
                    $account_money=[];//结算账户金额
                    $settle_type_name=[];//结算方式名称
                    $settle_sn=[];//结算号
                    $settle_mark=[];//结算分录备注
                  
                    foreach ($move_good as $ke => $va) {
                        $g_account_name=Db::name('account')->where('id',$va['account_id'])->value('name');
                        $g_settle_type_name=Db::name('settle_type')->where('id',$va['settle_type_id'])->value("name");
                        array_push($account_name,$g_account_name);
                        array_push($account_money,$va['account_money']);
                        array_push($settle_type_name,$g_settle_type_name);
                        array_push($settle_sn,$va['settle_sn']);
                        array_push($settle_mark,$va['mark']);
                    }
                    $val['account_name']=$account_name;
                    $val['account_money']=$account_money;
                    $val['settle_type_name']=$settle_type_name;
                    $val['settle_sn']=$settle_sn;
                    $val['settle_mark']=$settle_mark;
                    $val['col_h']=count($account_name);//行高
                    //$val['zt']=$val['status'];//行高
                    $val['dj_time'] = date('Y-m-d', $val['dj_time']); 
                    $c=Db::name('customer')->where('id',$val['user_id'])->find();
                    $val['saler_name']=Db::name('auth_user')->where('id',$val['saler'])->value('name');
                    $val['customer_name']=$c['sn'].' '.$c['name']; 
                    $val['add_user_name']=$val['add_user']==0? '' :Db::name('auth_user')->where('id',$val['add_user'])->value('name');
                    $val['shenhe_user_name']=$val['shenhe_user']==0? '' : Db::name('auth_user')->where('id',$val['shenhe_user'])->value('name');

            //halt($list);
                }
            return $this->grid_data($list, $count, $page, $limit);

        }
        $today=date('Y-m-d',time());
        $mon_start=date('Y-m',time()).'-01';
        $this->assign('today',$today);
        $this->assign('mon_start',$mon_start);
        return $this->fetch();
    }


    public function add()
    {
        $sn=money_sn('SKD');
        //结算账户
        // $account=Db::name('account')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->order('is_default desc,id asc')->select();  
        // //结算方式
        // $settle_type=Db::name('settle_type')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->order('id asc')->select();  
        //收款人
        $staff=Db::name('auth_user')->where('type',1)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->where('status',0)->order('id desc')->select();
        $today=date('Y-m-d',time());
        $this->assign('today',$today);
        $this->assign('sn',$sn);
        $this->assign('staff',$staff);
        // $this->assign('account',$account);
        // $this->assign('settle_type',$settle_type);
        return $this->fetch();
    }


     // 添加-更新
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();

        //halt($data);
        Db::startTrans(); // 启动事务
        $data['type']=0;//0收款单；1付款单
        $res=$this->inset_money_record($data);
        if($res==1){
            Db::commit();// 提交事务
            $status = 1;
            $msg = "添加成功";
        }else if($res==2){
            Db::rollback();// 回滚事务
            $msg = "存在相同的单据号";
        }else{
            Db::rollback();// 回滚事务
        }
        return ['status' => $status, 'msg' => $msg];
    }



     //审核与反审核
    public function shenhe() {
        $data=$this->request->param();
        $status=0;
        // intval(0);
        // exit();
        $msg="操作失败";
        $id=$data['id'];
        $type=$data['type'];
        Db::startTrans();// 启动事务
        $info=Db::name('payment')->where('id',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->find();
        //halt( $info);
        //if($info['xht_id']==0&&$info['xh_id']==0){
            if($type==1){
                if($info['status']==1){
                    $msg = "已审核过，不可审核";
                }else{
                    $update=[
                        'status'=>1,
                        'updatetime'=>time(),
                        'shenhe_time'=>time(),
                        'shenhe_user'=> $this->Userinfo['id'],
                        'last_user'=> $this->Userinfo['id'],
                    ];  
                    $result = Db::name('payment')->where('id',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->update($update);
                    if ($result) {
                       
                        //添加客户资金流水
                        $user_money['system_price']=0;//应收金额-优惠后的价格
                        $user_money['user_price']=$info['jine'];//实收金额-本次预收款
                        $user_money['user_id']=$info['user_id'];//客户ID
                        $user_money['type']=0;//0客户付款；1客户进款
                        $user_money['o_way']=4;// 0,销售单；1.销售退货单；2，采购单；3采购退货单；4收款单；5付款单;6,期初金额
                        $user_money['psn']=$info['sn'];
                        $user_money['pid']=$info['id'];
                        $user_money['enterprise_id']=$this->EnterpriseId;
                        $res1=add_user_money($user_money);
                        //存在本次预收款
                        if($info['now_jine']!=0){
                            $user_money['user_price']=$info['zk_jine'];//折扣金额
                            $user_money['is_pre']=1;
                            $res2=add_user_money($user_money);
                        }else{
                            $res2=1;
                        }
                        if ($res1==0||$res2==0) {
                            $msg = "参数错误";
                        }
                        if( $res1==1&&$res2==1){
                            $status = 1;
                            $msg = "操作成功";
                        }
                    }

                }
               
            }
            if($type==2){
                if($info['status']==0){
                    $msg = "已审核过，不可审核";
                }else{
                    $update=[
                        'status'=>0,
                        'updatetime'=>time(),
                        'shenhe_time'=>0,
                        'shenhe_user'=> 0,
                        'last_user'=> $this->Userinfo['id'],
                    ]; 
                    $result = Db::name('payment')->where('id',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->update($update);
                    if ($result) {
                        $upda=[
                            'is_del'=>1,
                            'updatetime'=>time(),
                            'last_user'=> $this->Userinfo['id'],
                        ];
                        $re=Db::name('user_money')->where('pid',$info['id'])->where('psn',$info['sn'])->where('is_del',0)->find(); 
                        if($re){
                            unset($upda['last_user']);
                            //删除客户资金流水
                            $resu1=del_user_money($upda,$info);
                            if($resu1==1){
                                $status = 1;
                                $msg = "操作成功";
                            }else{
                                $status=0;
                                $msg = "操作失败";
                            }

                        }
                       
                    }


                }
               
            }
        // }else {
        //     $msg="存在关联单据不能操作";
        // }
        if($status==1){
            Db::commit(); // 提交事务
        }else{
            Db::rollback(); // 回滚事务
        }
        return ['status'=>$status,'msg'=>$msg];
    }

    //删除
    public function del($id) {
        $status=0;
        $msg="删除失败";
        // 启动事务
        Db::startTrans();
        $info=Db::name('payment')->where('id',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->find();
        // halt( $info);
        if($info['status']!=1){
            $update=[
                'is_del'=>1,
                'updatetime'=>time(),
                'last_user'=> $this->Userinfo['id'],
            ]; 
            $result = Db::name('payment')->where('id',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->update($update);
            if ($result) {
                $c=Db::name('payment_good')->where('pid',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->select();
                if(!empty($c)){
                    $res = Db::name('payment_good')->where('pid',$id)->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->setField('is_del',1);
                    if ($res) {
                        Db::commit(); // 提交事务
                        $status=1;
                        $msg="删除成功";
                    } 
                }else{
                    Db::commit(); // 提交事务
                    $status=1;
                    $msg="删除成功";
                }
               
            }
        }else {
           // $msg="存在关联单据不能删除";
            $msg="已审核单据不能删除";
        }
        if($status!=1){
            // 回滚事务
            Db::rollback();
        }
        return ['status'=>$status,'msg'=>$msg];
    }

         //订单详情
    public function details() {
        $data=$this->request->param();
        $oid=$data['order_id'];
        $o = Db::name('payment')->where('id',$oid)->where('is_del',0)->find();
        $customer=Db::name('customer')->where('id',$o['user_id'])->find();
        $o['customer_name']=$customer['sn'].' '.$customer['name'];
        $o['saler_name']=Db::name('auth_user')->where('id',$o['saler'])->value('name');
        //halt($o);
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map='';
            $page=isset($data['page'])?$data['page']:1;
            $page=intval($page);
            $limit=isset($data['rows'])?$data['rows']:10;
            $limit=intval($limit);
            $start=$limit*($page-1);

        
            if($map==''){
                $list =Db::name('account_record')->where('pid',$o['id'])->where('psn',$o['sn'])->where('is_del',0)->order('addtime desc,id asc')->limit($start,$limit)->select();
                $count =Db::name('account_record')->where('pid',$o['id'])->where('psn',$o['sn'])->where('is_del',0)->count();
            }else{
                $list =Db::name('account_record')->where('pid',$o['id'])->where('psn',$o['sn'])->where('is_del',0)->order('sort desc,id asc')->limit($start,$limit)->select();
                $count =Db::name('account_record')->where('pid',$o['id'])->where('psn',$o['sn'])->where('is_del',0)->count();
            }

            foreach ($list as $key => &$val) {
                $g=Db::name('account')->where('id',$val['account_id'])->find();//结算账户
                $c=Db::name('settle_type')->where('id',$val['settle_type_id'])->find();//结算方式
                $val['account_name']=$g['name'];
                $val['settle_type_name']=$c['name'];
                $val['jine']=$val['account_money'];
                // $val['dw_name']=Db::name('unit')->where('id',$val['dw'])->value('name');
            
            }
            //halt($o);
            //少于5条则填充
            if(3-$count>0){
                for ($i=0; $i <3-$count ; $i++) { 
                    array_push($list, []);
                }
            }
          
            return $this->grid_data($list,$count,$page,$limit); 
        }

        if (isset($data['ajax']) && $data['ajax'] == 200) {
            $map='';
            $page=isset($data['page'])?$data['page']:1;
            $page=intval($page);
            $limit=isset($data['rows'])?$data['rows']:10;
            $limit=intval($limit);
            $start=$limit*($page-1);

        
            if($map==''){
                $list =Db::name('payment_good')->where('pid',$o['id'])->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->order('addtime desc,id asc')->limit($start,$limit)->select();
                $count =Db::name('payment_good')->where('pid',$o['id'])->where('enterprise_id',$this->EnterpriseId)->where('is_del',0)->count();
            }else{
                $list =Db::name('payment_good')->where('pid',$o['id'])->where('is_del',0)->order('sort desc,id asc')->where('enterprise_id',$this->EnterpriseId)->limit($start,$limit)->select();
                $count =Db::name('payment_good')->where('pid',$o['id'])->where('enterprise_id',$this->EnterpriseId)->where('is_del',0)->count();
            }

            foreach ($list as $key => &$val) {
                if(isset($val['o_id'])&&isset($val['o_sn'])){
                    $g=Db::name('order')->where('id',$val['o_id'])->where('sn',$val['o_sn'])->find();//订单
                    $val['psn']=$val['o_sn'];
                   
                 
                    
                   
                    $val['already_jine'] = floatval('0.00');
                   // $val['not_jine'] = $g['dj_jine'] - $g['already_jine'];
                    $val['type_name']=$g['o_type']==1? "普通销售" : "销售退回";
                    $val['dj_time']=date('Y-m-d',$g['dj_time']);
                    $val['dj_jine']=$g['o_type']==1?floatval($g['yh_price'])-floatval($g['payment']) : floatval($g['payment'])-floatval($g['yh_price']);
                    $val['jine']=sprintf("%.2f",$val['dj_jine']);
                    $val['already_jine']=floatval('0.00');
                    $val['not_jine']=$val['dj_jine']-$val['already_jine'];
                   // $val['shuliang']=$val['num'];
                   // $val['dw_name']=Db::name('unit')->where('id',$val['dw'])->value('name');

                }
                // 
                // 
                // $val['type_name']=$g['o_type']==1? "普通销售" : "销售退回";
                // $val['dj_time']=date('Y-m-d',$g['dj_time']);
                // $val['dj_jine']=$g['o_type']==1?floatval($g['yh_price'])-floatval($g['payment']) : floatval($g['payment'])-floatval($g['yh_price']);
                // $val['already_jine']=floatval('0.00');
                // $val['not_jine']=$g['dj_jine']-$g['already_jine'];
                // $val['shuliang']=$val['num'];
                // $val['dw_name']=Db::name('unit')->where('id',$val['dw'])->value('name');
            
            }
            //少于5条则填充
            if(5-$count>0){
                for ($i=0; $i <5-$count ; $i++) { 
                    array_push($list, []);
                }
            }
          
            return $this->grid_data($list,$count,$page,$limit); 
        }
        

      
        //收款人
        $staff=Db::name('auth_user')->where('is_del',0)->where('type',1)->where('enterprise_id',$this->EnterpriseId)->where('status',0)->order('id desc')->select();

        // //结算账户
        // $account=Db::name('account')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->order('is_default desc,id asc')->select();  
        // //结算方式
        // $settle_type=Db::name('settle_type')->where('is_del',0)->where('enterprise_id',$this->EnterpriseId)->order('id asc')->select();  
   
        // $this->assign('account',$account);
        // $this->assign('settle_type',$settle_type);
        $this->assign('staff',$staff);
     
        $this->assign('info',$o);
        return $this->fetch();
    }



}
